package com.yan.furns.service.impl;

import com.yan.furns.dao.FurnDAO;
import com.yan.furns.dao.OrderDAO;
import com.yan.furns.dao.OrderItemDAO;
import com.yan.furns.dao.impl.FurnDAOImpl;
import com.yan.furns.dao.impl.OrderDAOImpl;
import com.yan.furns.dao.impl.OrderItemDAOImpl;
import com.yan.furns.entity.*;
import com.yan.furns.service.OrderService;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author Yzb
 * @version 1.0
 */
public class OrderServiceImpl implements OrderService {
	private OrderDAO orderDAO = new OrderDAOImpl();
	private OrderItemDAO orderItemDAO = new OrderItemDAOImpl();
	private FurnDAO furnDAO = new FurnDAOImpl();

	@Override
	public String saveOrder(Cart cart, int memberId) {
		String orderId = System.currentTimeMillis() + "" + memberId;
		Order order = new Order(orderId, new Date(), cart.getTotalPrice(), 0, memberId);
		orderDAO.saveOrder(order);

		Map<Integer, CartItem> orderItems = cart.getItems();
		Set<Integer> keys = orderItems.keySet();
		for (Integer key : keys) {
			CartItem cartItem = orderItems.get(key);
			OrderItem orderItem = new OrderItem(null, cartItem.getName(), cartItem.getPrice(),
					cartItem.getCount(), cartItem.getTotalPrice(), orderId);

			orderItemDAO.saveOrderItem(orderItem);

			Furn furn = furnDAO.queryFurnById(cartItem.getId());
			furn.setSales(furn.getSales() + cartItem.getCount());
			furn.setStock(furn.getStock() - cartItem.getCount());
			furnDAO.updateFurn(furn);
		}

		cart.clear();
		return orderId;
	}

	@Override
	public List<Order> getOrderList(int memberId) {
		return orderDAO.getOrdersByMemberId(memberId);
	}

	@Override
	public List<OrderItem> getOrderItemList(String orderId) {
		return orderItemDAO.getOrderItemsByOrderId(orderId);
	}

	@Override
	public Order getOrderByOrderId(String orderId) {
		return orderDAO.getOrderByOrderId(orderId);
	}
}
